import 'package:dotted_border/dotted_border.dart';
import 'package:enter_prise_web/common/constants.dart';
import 'package:enter_prise_web/iconfont/icon_font.dart' as icon;
import 'package:enter_prise_web/models/group.dart';
import 'package:enter_prise_web/page/index/index_controller.dart';
import 'package:enter_prise_web/page/staff/staff_controller.dart';
import 'package:enter_prise_web/util/MyDio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../../iconfont/icon_font.dart';

class GroupListIndex extends StatefulWidget {
  const GroupListIndex(
      {super.key, required this.isMove, required this.groupName, this.uid});
  final bool isMove;
  final String groupName;
  final String? uid;

  @override
  State<GroupListIndex> createState() => _GroupListIndexState();
}

class _GroupListIndexState extends State<GroupListIndex> {
  final staffController s = Get.find<staffController>();
  int selectCount = 0;
  final IndexController c = Get.find();
  final MyDio myDio = MyDio();

  final TextEditingController _textEditingController =
      TextEditingController(text: "");

  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    groupName = widget.groupName;
  }

  late String groupName;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.isMove ? "移至分组" : "分组管理"),
        centerTitle: true,
        leading: widget.isMove
            ? IconButton(
                icon: const Icon(Icons.arrow_back), onPressed: () => Get.back())
            : Container(),
        actions: [
          !widget.isMove
              ? TextButton(
                  onPressed: () {
                    //获取到当前组别名称，并修改用户的组别
                    Get.until(
                      (route) => route.isFirst,
                    );
                  },
                  child: const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 12),
                    child: Text(
                      "完成",
                      style: TextStyle(color: Colors.black, fontSize: 24),
                    ),
                  ),
                )
              : Container()
        ],
      ),
      body: GetBuilder<staffController>(
          id: "group_list",
          builder: (gcontroller) {
            return Material(
              color: Colors.white,
              child: Column(
                children: [
                  GestureDetector(
                    onTap: () {
                      //弹出一个框
                      showCupertinoDialog(
                        context: Get.context!,
                        builder: (c) {
                          return CupertinoAlertDialog(
                            actions: [
                              CupertinoDialogAction(
                                child: const Text("取消"),
                                onPressed: () => Get.back(),
                              ),
                              CupertinoDialogAction(
                                child: const Text("确定"),
                                onPressed: () async {
                                  String msg = _textEditingController.text;
                                  //分割字符串
                                  List<String> list = msg.split("&");
                                  //判断是否为空

                                  if (list.length == 3) {
                                    //执行相关操作
                                    String gid = list[0];
                                    String groupName = list[1];
                                    String viewName = list[2];

                                    var response = await myDio
                                        .requestData('/group/add', method:'POST',params: {
                                      "gid": gid,
                                      "groupName": groupName,
                                      "viewName": viewName
                                    });
                                    print(response);
                                    if (response.data['message'] == '添加成功!') {
                                      Fluttertoast.showToast(msg: "添加成功!");
                                      s.refreshData();
                                      Get.back();
                                    }
                                  } else {
                                    Fluttertoast.showToast(msg: "请按格式填写信息");
                                  }
                                },
                              )
                            ],
                            title: const Text('添加分组'),
                            // content: "请按格式填写信息",
                            content: Container(
                              height: 50,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Scaffold(
                                body: Padding(
                                  padding: const EdgeInsets.only(
                                      left: 8.0, right: 8.0, top: 4.0),
                                  child: TextField(
                                    controller: _textEditingController,
                                    focusNode: _focusNode,
                                    autofocus: true,
                                    cursorColor: Colors.black,
                                    cursorWidth: 0.3,
                                    decoration: const InputDecoration(
                                        border: InputBorder.none,
                                        hintText: "uid&groupName&viewName"),
                                  ),
                                ),
                              ),
                            ),
                          );
                        },
                      );
                    },
                    child: Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(
                              left: 12.0, right: 12, top: 8.0),
                          child: DottedBorder(
                            color: kGrayColor,
                            borderType: BorderType.RRect,
                            radius: const Radius.circular(12),
                            child: const ClipRRect(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                              child: SizedBox(
                                height: 50,
                                width: 50,
                                child: Icon(
                                  Icons.add,
                                  size: 30,
                                  color: kGrayColor,
                                ),
                              ),
                            ),
                          ),
                        ),
                        const Text(
                          "添加分组",
                          style: TextStyle(color: Colors.black, fontSize: 20),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: ListView.builder(
                        itemCount: gcontroller.groups.length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () async {
                              var gid = gcontroller.groups[index]['gid'];
                              if (groupName ==
                                  gcontroller.groups[index]['name']) {
                                //已在当前分组
                                Fluttertoast.showToast(msg: '已在当前分组中');
                              } else {
                                //调用移动分组接口
                                var response =
                                    await myDio.requestData('/user/move',method: 'GET', params: {
                                  "uid": widget.uid,
                                  "gid": gid,
                                }).catchError((error) {
                                  print(error);
                                });

                                print(response.data);
                                if (response.data['code'] == 200 &&
                                    response.data['message'] == '移动成功!') {
                                  s.groupName.value =
                                      group.getGroupName(gid.toString())!;
                                  s.refreshData();
                                  //请求成功
                                  Fluttertoast.showToast(msg: '移动成功！');
                                } else {
                                  print(response.data['message']);
                                }
                              }
                              Get.back(result: 'move');
                            },
                            child: Container(
                                height: 60,
                                decoration: BoxDecoration(
                                    border: widget.isMove
                                        ? null
                                        : const Border(
                                            bottom: BorderSide(
                                                width: 1,
                                                color: Colors.black12))),
                                child: buildGroupIItem(
                                  gName: groupName,
                                  controller: gcontroller,
                                  index: index,
                                  isMove: widget.isMove,
                                )),
                          );
                        }),
                  ),
                ],
              ),
            );
          }),
    );
  }
}

class buildGroupIItem extends StatefulWidget {
  const buildGroupIItem(
      {super.key,
      required this.isMove,
      required this.controller,
      required this.index,
      required this.gName});
  final bool isMove;
  final staffController controller;
  final int index;
  final String gName;

  @override
  State<buildGroupIItem> createState() => _buildGroupIItemState();
}

class _buildGroupIItemState extends State<buildGroupIItem> {
//是否显示删除按钮
  bool isShow = true;

  void toggleVisibility() {
    setState(() {
      isShow = !isShow;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        widget.isMove
            ? const SizedBox.shrink()
            : Padding(
                padding: const EdgeInsets.only(left: 12),
                child: IconButton(
                    onPressed: () {
                      setState(() {
                        toggleVisibility();
                      });
                    },
                    icon: icon.IconFont(
                      IconNames.tingzhi_1,
                      size: 22,
                    )),
              ),
        Padding(
          padding: const EdgeInsets.only(left: 12.0),
          child: Text(
            widget.controller.groups[widget.index]['name'],
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w400),
          ),
        ),
        Expanded(
          child: Container(),
        ),
        !widget.isMove
            ? Stack(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 12),
                      child: TextButton(
                        onPressed: () {},
                        style: ButtonStyle(
                            backgroundColor: MaterialStateColor.resolveWith(
                          (states) {
                            return const Color(0xfffa6159);
                          },
                        )),
                        child: const Text(
                          "删除",
                          style: TextStyle(color: Colors.white, fontSize: 17),
                        ),
                      )),
                  AnimatedContainer(
                    duration: const Duration(milliseconds: 100),
                    width: isShow ? 70 : 0,
                    color: Colors.white,
                    child: Container(),
                  ),
                ],
              )
            : widget.gName == widget.controller.groups[widget.index]['name']
                ? Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: icon.IconFont(
                      IconNames.duigou_cu,
                      size: 30,
                    ))
                : const SizedBox.shrink()
      ],
    );
  }
}
